import {ref, watch} from 'vue'
import {cityAPI} from '@/api/city'

// 添加防抖函数
function useDebounce(fn, delay) {
    let timer = null
    return (...args) => {
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
            fn.apply(this, args)
        }, delay)
    }
}

export function useSearchCity() {
    const citySearchText = ref("")
    const filteredCities = ref([])
    const loading = ref(false)

    const searchCities = async (searchText) => {
        if (!searchText) {
            filteredCities.value = []
            return
        }

        try {
            loading.value = true
            const result = await cityAPI.searchCities(searchText)
            filteredCities.value = result
        } catch (error) {
            console.error('搜索城市失败:', error)
            // 这里可以添加特定的错误处理逻辑
            // Toast 已经在 request.js 中统一处理了
        } finally {
            loading.value = false
        }
    }

    // 使用防抖来优化搜索
    const debounceSearch = useDebounce(searchCities, 300)

    watch(citySearchText, (newValue) => {
        debounceSearch(newValue)
    })

    return {
        citySearchText,
        filteredCities,
        loading
    }
}